package com.qd.system.service.article;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.excel.ExcelExport;
import com.cdqidi.excel.util.ExportPage;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.DateUtil;
import com.cdqidi.util.RedisTemplateUtil;
import com.cdqidi.util.page.PageUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qd.common.sys.domain.entity.article.ArticleContentDTO;
import com.qd.common.sys.domain.entity.article.ArticleDTO;
import com.qd.common.sys.domain.entity.article.ArticleFileDTO;
import com.qd.common.sys.domain.entity.upload.FileUploadDTO;
import com.qd.common.sys.enums.BaseTableEnum;
import com.qd.common.sys.util.SecurityUtils;
import com.qd.system.mapper.ArticleMapper;
import com.qd.system.model.Article;
import com.qd.system.model.ArticleContent;
import com.qd.system.model.ArticleFile;
import com.qd.system.service.dict.MbUtil;
import com.qd.system.service.org.OrgService;
import com.qd.system.service.person.PersonService;
import com.qd.system.service.user.UserOperatorService;
import com.qd.system.util.FileConfirmUtil;
import com.qd.upload.constant.FileConfirmDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * 内容发布
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class ArticleService extends BaseService<ArticleMapper, Article> {

    private static final String PREFIX_ID = "sys_article_articleId_{0}";
    private static final String PREFIX_HINT_COUNT = "sys_article_hint_count_articleId_{0}";

    private final RedisTemplateUtil<Article> redisTemplateUtil;
    private final ObjectMapper objectMapper;
    private final HttpServletResponse response;
    private final OrgService orgService;
    private final PersonService personService;
    private final ArticleContentService articleContentService;
    private final ArticleFileService articleFileService;


    @Transactional(rollbackFor = Exception.class)
    public ArticleDTO saveArticle(ArticleDTO dto) {
        checkMb(dto);
        dto.setArticleId(IdWorker.getIdStr());
        String content = dto.getContent();
        List<ArticleFile> articleFiles = buildArticleFiles(dto);
        if (!articleFiles.isEmpty()) {
            articleFileService.saveBatch(articleFiles);
        }
        dto.setCreateTime(LocalDateTime.now());
        if (StringUtils.hasLength(content)) {
            ArticleContentDTO articleContent = new ArticleContentDTO();
            articleContent.setArticleId(dto.getArticleId());
            articleContent.setContent(content);
            articleContentService.save(articleContent);
        }
        return save(dto);
    }

    @Transactional(rollbackFor = Exception.class)
    public ArticleDTO updateArticle(ArticleDTO dto) {
        checkMb(dto);
        if (StringUtils.hasLength(dto.getContent())) {
            ArticleContentDTO articleContent = new ArticleContentDTO();
            articleContent.setArticleId(dto.getArticleId());
            articleContent.setContent(dto.getContent());
            articleContentService.update(articleContent);
        }
        List<ArticleFile> articleFiles = buildArticleFiles(dto);
        if (!articleFiles.isEmpty()) {
            articleFiles.forEach(articleFile -> {
                if (Boolean.TRUE.equals(articleFileService.isExistsById(articleFile.getDocId()))) {
                    articleFileService.update(articleFileService.modelToDto(articleFile));
                } else {
                    articleFileService.save(articleFileService.modelToDto(articleFile));
                }
            });
        }
        return update(dto);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteArticle(List<String> ids) {
        ids.forEach(articleId -> {
            List<ArticleFile> list = articleFileService.getList(articleId);
            if (!list.isEmpty()) {
                list.forEach(articleFile -> {
                    FileConfirmUtil.deleteFileConfirm(articleFile.getDocPath());
                    articleFileService.removeById(articleFile.getDocId());
                });
            }
            articleContentService.removeById(articleId);
            removeById(articleId);
        });

    }

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public ArticleDTO save(ArticleDTO dto) {
        buildBase(dto);
        final Article model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public ArticleDTO update(ArticleDTO dto) {
        buildBase(dto);
        check(dto);
        final Article historyModel = Optional.ofNullable(getById(dto.getArticleId())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final Article model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 删除，单个
     *
     * @param articleId 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String articleId) {
        final Article model = getById(articleId);
        if (null == model) {
            throw new ApiException("数据不存在,不能删除");
        }
        check(modelToDto(model));
        try {
            if (!super.removeById(articleId)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(ArticleDTO dto) {
        final QueryWrapper<Article> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param articleId 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String articleId) {
        boolean exists = false;
        if (StringUtils.hasLength(articleId)) {
            final Article model = getById(articleId);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param articleId 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public Article getById(String articleId) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, articleId);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(articleId), Article.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param articleId 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public ArticleDTO getByIdDto(String articleId) {
        final Article model = getById(articleId);
        if (null != model) {
            return modelToDto(model);
        }
        return null;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public Article getOne(ArticleDTO dto) {
        final QueryWrapper<Article> queryWrapper = createQueryWrapper(dto);
        Article model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public ArticleDTO getOneDto(ArticleDTO dto) {
        final Article model = getOne(dto);
        if (null == model) {
            return null;
        }
        final ArticleDTO newDto = modelToDto(model);
        model.freeData();
        return newDto;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<Article> getList(ArticleDTO dto) {
        final QueryWrapper<Article> queryWrapper = createQueryWrapper(dto);
        final List<Article> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<ArticleDTO> getListDto(ArticleDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<ArticleDTO> page(Page<Article> page, ArticleDTO dto) {
        final LocalDate now = LocalDate.now();
        if (dto.getType() == 1) {
            dto.setIsPublish(ConstantDto.SF1);
            if (StringUtils.hasLength(dto.getBeginTime()) && DateUtil.strToLocalDate(dto.getBeginTime()).isAfter(now)) {
                throw new ApiException("开始时间不能大于当前时间");
            }
            if (StringUtils.hasLength(dto.getEndTime()) && DateUtil.strToLocalDate(dto.getEndTime()).isAfter(now)) {
                throw new ApiException("结束时间不能大于当前时间");
            }
        }
        final QueryWrapper<Article> queryWrapper = createQueryWrapper(dto, "art.");
        if (dto.getType() == 1 && !StringUtils.hasLength(dto.getBeginTime()) || !StringUtils.hasLength(dto.getEndTime())) {
            queryWrapper.le("art.report_time", now);
        }
        UserOperatorService.buildInSql(dto, queryWrapper);
        final IPage<ArticleDTO> iPage = baseMapper.page(page, queryWrapper);
        queryWrapper.clear();
        return iPage;
    }

    @Transactional(readOnly = true)
    public IPage<ArticleDTO> appPage(Page<Article> page, ArticleDTO dto) {
        final LocalDate now = LocalDate.now();
        final QueryWrapper<Article> queryWrapper = createQueryWrapper(dto, "art.");
        if (dto.getType() == 1 && !StringUtils.hasLength(dto.getBeginTime()) || !StringUtils.hasLength(dto.getEndTime())) {
            queryWrapper.le("art.report_time", now);
        }
        final IPage<ArticleDTO> iPage = baseMapper.page(page, queryWrapper);
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 导出Excel
     *
     * @param query 查询条件
     * @throws IOException 异常
     */
    @Transactional(readOnly = true)
    public void export(ArticleDTO query) throws IOException {
        final ExportPage<Article, ArticleDTO> exportPage = new ExportPage<>();
        final List<ArticleDTO> list = exportPage.getAllForPage(page -> page(page, query).getRecords());
        try {
            ExcelExport.downloadExcel(response, ArticleDTO.class, () -> list);
            list.clear();
        } catch (IOException e) {
            log.error("导出失败", e);
            throw new ApiException("导出失败");
        }
    }


    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(Article model) {
        if (null == model) {
            return;
        }
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getArticleId());
        redisTemplateUtil.deleteByKey(key);
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public ArticleDTO modelToDto(Article model) {
        if (null == model) {
            return null;
        }
        final ArticleDTO dto = new ArticleDTO();
        dto.setArticleId(model.getArticleId());
        dto.setTitle(model.getTitle());
        dto.setCreateTime(model.getCreateTime());
        dto.setReportTime(model.getReportTime());
        dto.setSummary(model.getSummary());
        dto.setHintCount(model.getHintCount());
        dto.setOrgId(model.getOrgId());
        dto.setPersonId(model.getPersonId());
        dto.setArticleType(model.getArticleType());
        dto.setIsPublish(model.getIsPublish());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public Article dtoToModel(ArticleDTO dto) {
        if (null == dto) {
            return null;
        }
        final Article model = new Article();
        model.setArticleId(dto.getArticleId());
        model.setTitle(dto.getTitle());
        model.setCreateTime(dto.getCreateTime());
        model.setReportTime(dto.getReportTime());
        model.setSummary(dto.getSummary());
        model.setHintCount(dto.getHintCount());
        model.setOrgId(dto.getOrgId());
        model.setPersonId(dto.getPersonId());
        model.setArticleType(dto.getArticleType());
        model.setIsPublish(dto.getIsPublish());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(ArticleDTO dto) {
        dto.setOrgIdDisplay(orgService.idToDisplay(dto.getOrgId()));
        dto.setPersonIdDisplay(personService.idToDisplay(dto.getPersonId()));
        dto.setArticleTypeDisplay(MbUtil.idToDisplay(dto.getArticleType()));
        dto.setIsPublishDisplay(MbUtil.idToDisplay(dto.getIsPublish()));
        ArticleContent articleContent = articleContentService.getById(dto.getArticleId());
        if (null != articleContent) {
            dto.setContent(articleContent.getContent());
        }
        List<ArticleFileDTO> articleFiles = articleFileService.getListDto(dto.getArticleId());
        if (null != articleFiles && !articleFiles.isEmpty()) {
            dto.setFileList(articleFiles);
        }
        dto.setHintCount(getHintCount(dto.getArticleId()));
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<ArticleDTO> modelToDtoList(List<Article> list) {
        if (null == list) {
            return Collections.emptyList();
        }
        return list.stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<Article> dtoToModelList(List<ArticleDTO> list) {
        if (null == list) {
            return Collections.emptyList();
        }
        return list.stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<Article> createQueryWrapper(ArticleDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<Article> createQueryWrapper(ArticleDTO dto, String tableAlias) {
        final QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias) && tableAlias.charAt(tableAlias.length() - 1) != '.') {
                tableAlias += ".";
            }
            if (StringUtils.hasLength(dto.getTitle())) {
                queryWrapper.like(tableAlias + "title", dto.getTitle());
            }
            if (StringUtils.hasLength(dto.getSummary())) {
                queryWrapper.like(tableAlias + "summary", dto.getSummary());
            }
            if (StringUtils.hasLength(dto.getOrgId())) {
                queryWrapper.eq(tableAlias + "org_id", dto.getOrgId());
            }
            if (StringUtils.hasLength(dto.getArticleType())) {
                queryWrapper.eq(tableAlias + "article_type", dto.getArticleType());
            }
            if (StringUtils.hasLength(dto.getIsPublish())) {
                queryWrapper.eq(tableAlias + "is_publish", dto.getIsPublish());
            }
            if (StringUtils.hasLength(dto.getBeginTime())) {
                queryWrapper.apply("date_format(" + tableAlias + "report_time,'%Y-%m-%d') >= {0}", dto.getBeginTime());
            }
            if (StringUtils.hasLength(dto.getEndTime())) {
                queryWrapper.apply("date_format(" + tableAlias + "report_time,'%Y-%m-%d') <= {0}", dto.getEndTime());
            }
        }
        queryWrapper.orderByDesc(tableAlias + "create_time");
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     */
    public void checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            return;
        }
        final List<Article> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        final List<String> notExistsList = ids.stream().filter(id -> !list.stream().map(Article::getArticleId).collect(toList()).contains(id)).collect(toList());
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
    }

    public void buildBase(ArticleDTO ArticleDTO) {
        final String currentOrgId = SecurityUtils.getLoginUser().getCurrentOrgId();
        final String userId = SecurityUtils.getLoginUser().getUserId();
        if (!StringUtils.hasLength(ArticleDTO.getOrgId())) {
            ArticleDTO.setOrgId(currentOrgId);
        }
        if (!StringUtils.hasLength(ArticleDTO.getPersonId())) {
            ArticleDTO.setPersonId(userId);
        }
    }

    @Transactional(readOnly = true)
    public void check(ArticleDTO dto) {
        final Article article = getById(dto.getArticleId());
        if (null == article) {
            throw new ApiException("ID不存在[" + dto.getArticleId() + "]");
        }
        final String userId = SecurityUtils.getLoginUser().getUserId();
        if (!userId.equals(article.getPersonId())) {
            throw new ApiException("没有权限操作");
        }
    }

    private void checkMb(ArticleDTO dto) {
        if (MbUtil.isNotExists(dto.getIsPublish(), BaseTableEnum.SF)) {
            throw new ApiException("是否发布输入错误[" + dto.getIsPublish() + "]");
        }
        if (MbUtil.isNotExists(dto.getArticleType(), BaseTableEnum.ARTICLE_TYPE)) {
            throw new ApiException("题材分类输入错误[" + dto.getArticleType() + "]");
        }
    }


    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        ids.forEach(this::removeById);
    }

    private List<ArticleFile> buildArticleFiles(ArticleDTO ArticleDTO) {
        String articleId = ArticleDTO.getArticleId();
        List<FileUploadDTO> fileList = ArticleDTO.getFiles();
        List<ArticleFile> list;
        if (null == fileList || fileList.isEmpty()) {
            list = Collections.emptyList();
        } else {
            list = fileList.stream().map(fileUploadDTO -> {
                if (MbUtil.isNotExists(fileUploadDTO.getAttachmentType(), BaseTableEnum.ATTACHMENT_TYPE)) {
                    throw new ApiException("附件类型错误[" + fileUploadDTO.getAttachmentType() + "]");
                }
                FileConfirmDTO fileConfirmDto = FileConfirmUtil.singleFileConfirm(fileUploadDTO.getId(), fileUploadDTO.getAttachmentType());
                if (null == fileConfirmDto) {
                    throw new ApiException("文件ID不存在[" + fileUploadDTO.getId() + "]");
                }
                ArticleFile articleFile = new ArticleFile();
                articleFile.setArticleId(articleId);
                articleFile.setDocId(fileUploadDTO.getId());
                if (null != fileUploadDTO.getIdx() && fileUploadDTO.getIdx() > 0) {
                    articleFile.setIdx(fileUploadDTO.getIdx());
                }
                articleFile.setDocPath(fileConfirmDto.getOfficialFile());
                articleFile.setDocName(fileConfirmDto.getFileName());
                articleFile.setDocSize(fileConfirmDto.getFileSize());
                articleFile.setAttachmentType(fileUploadDTO.getAttachmentType());
                return articleFile;
            }).collect(toList());
        }
        return list;
    }

    /**
     * 增加点击数量
     *
     * @param articleId 文章ID
     */
    @Transactional(readOnly = true)
    public void addHintCount(String articleId) {
        String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_HINT_COUNT, articleId);
        final Long increment = redisTemplateUtil.getStringRedisTemplate().opsForValue().increment(key);
        final Article article = getById(articleId);
        if (log.isDebugEnabled()) {
            log.debug("标题： {},点击数量: {}", article.getTitle(), increment);
        }
    }

    public long getHintCount(String articleId) {
        String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_HINT_COUNT, articleId);
        String increment = redisTemplateUtil.getStringRedisTemplate().opsForValue().get(key);
        if (StringUtils.hasLength(increment)) {
            return Long.parseLong(increment);
        }
        return 0;
    }

    @Transactional(rollbackFor = Exception.class)
    public void batchUpdateHintCount() {
        String pattern = PREFIX_ID.substring(0, PREFIX_ID.indexOf("{"));
        final List<String> keyList = new ArrayList<>(redisTemplateUtil.scan(pattern));
        int total = keyList.size();
        final Page<Article> page = PageUtil.createPage(1L, 1000L);
        page.setTotal(total);
        page.setSearchCount(false);
        List<Article> dataList = new ArrayList<>(total);
        search(keyList, page, dataList);
        if (!dataList.isEmpty()) {
            updateBatchById(dataList, 1000);
        }
    }

    public void search(List<String> keyList, Page<Article> page, List<Article> dataList) {
        List<String> pageKey = PageUtil.page(keyList, (int) page.getTotal(), (int) page.getCurrent(), (int) page.getSize());
        List<String> jsonStr = redisTemplateUtil.getStringRedisTemplate().opsForValue().multiGet(pageKey);
        if (null == jsonStr || jsonStr.isEmpty()) {
            return;
        }
        List<Article> list = jsonStr.stream().map(str -> {
            try {
                return objectMapper.readValue(str, Article.class);
            } catch (JsonProcessingException ignored) {
            }
            return null;
        }).filter(Objects::nonNull).map(article -> {
            Article a = new Article();
            a.setArticleId(article.getArticleId());
            a.setHintCount(getHintCount(article.getArticleId()));
            return a;
        }).collect(Collectors.toList());
        if (!list.isEmpty()) {
            dataList.addAll(list);
        }
        if (!page.hasNext()) {
            return;
        }
        page.setCurrent(page.getCurrent() + 1);
        search(keyList, page, dataList);
    }

}